import PIL.Image as Image
import gradio as gr
from ultralytics import YOLO
import matplotlib
matplotlib.use('TkAgg')

model = YOLO("./best.pt")

def predict_image(img, conf_threshold):
    results = model.predict(
        source=img,
        conf=conf_threshold,
        show_labels=True,
        show_conf=True,
        imgsz=640
    )

    for r in results:
        im_array = r.plot()
        im = Image.fromarray(im_array[..., ::-1])

    return im

interface = gr.Interface(
    fn=predict_image,
    inputs=[
        gr.Image(type="pil", label="上传照片"),
        gr.Slider(minimum=0, maximum=1, value=0.40, label="置信度")
    ],
    outputs=gr.Image(type="pil", label="Result"),
    title="农作物病虫症状检测",
    description='''目前支持的农作物病状检测有：
    苹果叶,苹果锈病叶,苹果黑星病叶,灯笼椒叶,灯笼椒叶斑病,蓝莓叶,樱桃叶,玉米灰斑病叶,玉米叶枯病,玉米锈病叶,葡萄叶,葡萄黑腐病叶,
    桃树叶,马铃薯叶,马铃薯早疫病叶,马铃薯晚疫病叶,覆盆子叶,大豆叶,西葫芦白粉病叶,草莓叶,番茄早疫病叶,番茄叶,番茄叶细菌斑点病,
    番茄晚疫病叶,番茄叶花叶病毒病,番茄黄化曲叶病毒病,番茄霉病叶,番茄褐斑病叶,番茄二斑叶螨叶''',
    examples=[
        ["./samples/1.jpg", 0.40],
        ["./samples/2.jpg", 0.40],
        ["./samples/3.jpg", 0.40],
        ["./samples/4.jpg", 0.40],
        ["./samples/5.jpg", 0.40],
        ["./samples/6.jpg", 0.40],
        ["./samples/7.jpg", 0.40],
        ["./samples/8.jpg", 0.40],
        ["./samples/9.jpg", 0.40],
        ["./samples/10.jpg", 0.40],
        ["./samples/11.jpg", 0.40],
        ["./samples/12.jpg", 0.40],
        ["./samples/13.jpg", 0.40],
        ["./samples/14.jpg", 0.40],
        ["./samples/15.jpg", 0.40],
        ["./samples/16.jpg", 0.40],
        ["./samples/17.jpg", 0.40],
        ["./samples/18.jpg", 0.40],
        ["./samples/19.jpg", 0.40],
        ["./samples/20.jpg", 0.40],
        ["./samples/21.jpg", 0.40],
        ["./samples/22.jpg", 0.40],
        ["./samples/23.jpg", 0.40],
        ["./samples/24.jpg", 0.40],
        ["./samples/25.jpg", 0.40],
        ["./samples/26.jpg", 0.40],
    ]
)

if __name__ == "__main__":
    interface.launch()
